#include "PreHeader.h"
#include "LayerMain.h"
#include "LayerLogo.h"
#include "GlobalData.h"
#include "HBUtilies.h"
#include "DialogScore.h"
#include "DataSL.h"
#include "ExplodeScore.h"

CCScene* LayerMain::scene()
{
    CCScene *pScene = CCScene::create();
    LayerMain *layer = LayerMain::create();
    pScene->addChild(layer);
    
    return pScene;
}

bool LayerMain::init()
{
    CCLayer::init();
    
    setTouchEnabled(true);
    setKeypadEnabled(true);
    
    float w2 = 160;
    float h2 = 240;
    
    CCSprite* bg = createImage(fcs("Bg%d.jpg", rand() % 6 + 1), w2, h2, this);
    HBSetRatioScale(bg);

    // Time Bar
    CCSprite* sprite = createImageWithFrameName("level_bar.png", 0, 445 - kStartPos, this);
    sprite->setAnchorPoint(gAnchorLeft);
    HBSetRatioScale(sprite);
    mTimeBar = createImage("time_bar.png", 44, 412 - kStartPos, this);
    HBSetRatioScale(mTimeBar);
    mTimeBar->setAnchorPoint(ccp(0,0));
    mTimeValue = createLabel(fcs("%0.2f", 10), getLocalizedString("fontNormal"), 14, gAnchorCenter, ccYELLOW, 140, 432.5 - kStartPos, this);
    mLabelLevel = createLabel("Lv.1", getLocalizedString("fontNormal"), 20, gAnchorCenter, ccYELLOW, 36, 445 - kStartPos, this);

    // Next Goal:
    createLabel(getLocalizedString("Next Goal:"), getLocalizedString("fontNormal"), 26, gAnchorRight, ccYELLOW, 265, 460 - kStartPos, this);
    mLabelGoal = createLabel(fcs("%d", 60), getLocalizedString("fontNormal"), 26, gAnchorLeft, ccWHITE, 268, 460 - kStartPos, this);
    
    // High Score
    createLabel(getLocalizedString("High:"), getLocalizedString("fontNormal"), 24, gAnchorRight, ccYELLOW, 250, 80 - kStartPos, this);
    mLabelHigh = createLabel(fcs("%d", gHighScore[gFingerCount]), getLocalizedString("fontNormal"), 26, gAnchorLeft, ccWHITE, 253, 80 - kStartPos, this);
    
    // Score
    mScoreTotal = createLabelAtlas(fcs("%d", 0), "font_number.png", 56, 74, '0', w2, 370 - kStartPos, gAnchorCenter, this);
    
    if (gGameMode == kGameModeTest)
    {
        gFingerCount = gLevelDetail[gTestLevel].finger;
        mLevelTime = gLevelDetail[gTestLevel].time;
    }
    else
    {
        mLevelTime = 10.0f;
    }
    
    if(gFingerCount == kFingerOne)
    {
        mCircle[0] = createImage("TapBtn.png", w2, kCircleY - kStartPos, this);
    }
    else
    {
        mCircle[0] = createImage("TapBtn.png", 80, kCircleY - kStartPos, this);
        mCircle[1] = createImage("TapBtn.png", 240, kCircleY - kStartPos, this);
    }
		
    // Tips
    mTips = createLabel(getLocalizedString("TOUCH TO START"), getLocalizedString("fontNormal"), 30, gAnchorCenter, ccYELLOW, w2, 365 - kStartPos, this);
		
    // Menu
    CCMenu* menu = createMenu(this);
    CCMenuItem* item;
    
	item = createMenuItemWithCache("btn_normal.png", "btn_normal_d.png", 80, 80 - kStartPos, 0, menu, this, menu_selector(LayerMain::_back));
    addMenuLabelWithStroke(item, getLocalizedString("<< Back"), getLocalizedString("fontNormal"), 24, ccYELLOW, 1, ccBLACK);    
    
    // Finish
    mFinish = createLabel(getLocalizedString("FINISH"), getLocalizedString("fontNormal"), 72, gAnchorCenter, ccYELLOW, w2, 365 - kStartPos, this);
    
	scheduleUpdate();
    _restart();

	return true;
}

void LayerMain::update(float dt)
{
    if (mGameState == kStateBegin)
    {
        mLastTime -= dt;
        mTotalTime += dt;
        if (mLastTime <= 0)
        {
            mLastTime = 0;
            mGameState = kStateResult;
            mCircle[0]->setVisible(false);
            
            if(gFingerCount == kFingerTwo)
                mCircle[1]->setVisible(false);
            
            SimpleAudioEngine::sharedEngine()->playEffect("Done.wav");
            mFinish->runAction(CCSequence::create(CCSpawn::create(CCFadeIn::create(0.5), CCMoveBy::create(0.5, ccpRatio(0, -50)), NULL), CCDelayTime::create(0.3), CCCallFunc::create(this, callfunc_selector(LayerMain::_showResult)), NULL));
        }
    
        _updateTimeBar();
    }
}

void LayerMain::_showResult()
{
    DialogScore::create(mTotalCount, this);
    _restart();
}

void LayerMain::_updateTimeBar()
{
    float pos = mLastTime / mLevelTime;
    mTimeBar->setTextureRect(HBRectRatio(0, 0, MAX(10,pos * 170 + 10), 37));
    mTimeValue->setString(fcs("%.02f", mLastTime));
    float rate = 0;
    if (mTotalTime > 0)
    {
        rate = mTotalCount / mTotalTime * 60;
    }
}

void LayerMain::_updateLevel()
{
    mLabelLevel->setString(fcs("Lv.%d", mCurrentLevel));
    mLabelGoal->setString(fcs("%d", mNextGoal));
}

void LayerMain::_restart()
{
    // init data
    if (gGameMode == kGameModeTest)
    {
        mCurrentLevel = gTestLevel+1;
        mNextGoal = gLevelDetail[gTestLevel].goal;
    }
    else
    {
        mCurrentLevel = 1;
        mNextGoal = (kFingerOne == gFingerCount) ? 50 : 100;
    }
    
    mTotalTime = 0;
    
    _updateLevel();
    
	mTimeBar->setTextureRect(HBRectRatio(0, 0, 197, 37));

	mTimeValue->setString(fcs("%.02f", mLevelTime));
	mScoreTotal->setString("0");
	mCircle[0]->setVisible(true);
    
	if(gFingerCount == kFingerTwo)
	{
		mCircle[1]->setVisible(true);
	}
	
    mTips->setPosition(ccpRatio(160, 315 - kStartPos));
	mTips->setOpacity(255);
    mTips->setColor(ccYELLOW);
    mTips->runAction(CCRepeatForever::create((CCActionInterval*)CCSequence::create(CCTintTo::create(1, 0, 0, 255), CCTintTo::create(1, 255, 255, 0), NULL)));
    
	mTouchState[0] = mTouchState[1] = kTouchUngrabbed;
	mTouchCount[0] = mTouchCount[1] = mTotalCount = 0;
	mGameState = kStateNone;
    
	mFinish->setPosition(ccpRatio(160,350 - kStartPos));
	mFinish->setOpacity(0);
    
    mLabelHigh->setString(fcs("%d", gHighScore[gFingerCount]));
}

int LayerMain::_containsTouchLocation(CCTouch* touch)
{
	CCPoint location = touch->getLocation();

	if(ccpDistance(mCircle[0]->getPosition(), location) <= ccFontRatio(kCircleRadius))
		return 0;
	else if(gFingerCount == kFingerTwo)
    {
        if( ccpDistance(mCircle[1]->getPosition(), location) <= ccFontRatio(kCircleRadius))
            return 1;
	}
    
	return 2;
}

void LayerMain::_doTouch(int index, CCTouch* touch)
{
    if(mTouchState[index] != kTouchGrabbed)
    {
        mTouchState[index] = kTouchGrabbed;
        mTouch[index] = touch;
        mTouchCount[index] ++;
        mTotalCount = mTouchCount[0] + mTouchCount[1];
        mCircle[index]->runAction(CCSequence::create(CCScaleTo::create(0.02, 0.8), CCScaleTo::create(0.02, 1.0), NULL));
        
        CCPoint pos;
        if (kFingerTwo == gFingerCount)
            pos = ccpRatio(80 + index * 160, kCircleY + 30 - kStartPos);
        else
            pos = ccpRatio(160, kCircleY + 30 - kStartPos);

        ExplodeScore* s = new ExplodeScore(pos, mTouchCount[index], 20, ccYELLOW);
        addChild(s);
        
        mScoreTotal->setString(fcs("%d", mTotalCount));
        
        if (mTotalCount >= mNextGoal && kGameModeTest != gGameMode)
        {
            mCurrentLevel++;
            mLastTime += 1.5;
            mNextGoal += (kFingerOne == gFingerCount) ? 15 : 30 + (mCurrentLevel - 1);
            _updateTimeBar();
            _updateLevel();
            SimpleAudioEngine::sharedEngine()->playEffect("upgrade.m4a");
        }
    }
}

bool LayerMain::_checkTouch(CCSet *pTouches)
{
    bool isTouch = false;
    for (CCSetIterator itr = pTouches->begin(); itr != pTouches->end(); ++itr)
    {
        CCTouch* touch = (CCTouch*)*itr;
        int touchIn = _containsTouchLocation(touch);
        if(touchIn == 2 )
            continue;
        else if(touchIn == 0)
        {
            isTouch = true;
            _doTouch(0, touch);
        }
        else if(touchIn == 1)
        {
            isTouch = true;
            _doTouch(1, touch);
        }
    }
    
    return isTouch;
}

void LayerMain::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
	switch(mGameState)
	{
	case kStateNone:
        if(_checkTouch(pTouches))
        {
            SimpleAudioEngine::sharedEngine()->playEffect("Tap.wav");
            mGameState = kStateBegin;
            mLastTime = mLevelTime;
            mTips->runAction(CCSpawn::create(CCFadeOut::create(0.3), CCMoveBy::create(0.3, ccpRatio2(0,50)), NULL));
        }
        break;
    case kStateBegin:
        if(_checkTouch(pTouches)) 
            SimpleAudioEngine::sharedEngine()->playEffect("Tap.wav");
        break;
    default:
        break;
	}
}

void LayerMain::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
	switch(mGameState)
	{
    case kStateBegin:
        for (CCSetIterator itr = pTouches->begin(); itr != pTouches->end(); ++itr)
        {
            CCTouch* touch = (CCTouch*)*itr;
            if(touch == mTouch[0])
            {
                mTouchState[0] = kTouchUngrabbed;
                mTouch[0] = NULL;
            }
            else if(touch == mTouch[1])
            {
                mTouchState[1] = kTouchUngrabbed;
                mTouch[1] = NULL;
            }
        }
        break;
    default:
        break;
	}
}

void LayerMain::_back()
{
    SimpleAudioEngine::sharedEngine()->playEffect("Menu.wav");
    CCDirector::sharedDirector()->replaceScene(LayerLogo::scene());
}

void LayerMain::_retry()
{
    SimpleAudioEngine::sharedEngine()->playEffect("Menu.wav");
	_restart();
}

void LayerMain::registerWithTouchDispatcher()
{
    CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this,0);
}

void LayerMain::keyBackClicked()
{
	_back();
}

void LayerMain::keyMenuClicked()
{

}
